﻿#define _CRT_SECURE_NO_WARNINGS
//// C++ 推荐方式: 匿名命名空间
//namespace {  //<--- 匿名命名空间开始                 
//	int internal_counter = 0; //默认具有内部链接
//
//	void internal_helper() {  // 默认具有内部链接
//		// ...
//	}
//} // <--- 匿名命名空间结束
//
//// C++ 不推荐方式 (但仍然有效): static
//// static int old_style_counter = 0;
//// static void old_style_helper() { /* ... */ }
//
//void public_api() {
//	internal_helper(); // 可以直接调用同一编译单元内的匿名命名空间成员
//}
//int main()
//{
//	public_api();
//	return 0;
//}


#include<iostream>
#include<thread>
#include<vector>

class Singleton {
public:
	static Singleton& getInstance() {
		// C++11 guarantees thread-safe initialization for function-local statics
		static Singleton instance;

		std::cout << "获取单例线程:thread " << std::this_thread::get_id() << std::endl;
		return instance;
	}
	void showMessage() {
		std::cout << "单例调用:(" << std::this_thread::get_id() << ") says hello!" << std::endl;
	}
	~Singleton() = default;
private:

	//单例模式要求不能在类外部直接创建单例对象，必须通过Singleton::getInstance()创建
	//所以构造函数私有
	Singleton() {
		std::cout << "单例创建: thread " << std::this_thread::get_id() << std::endl;
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
	}
	//单例模式不允许该类被拷贝
	Singleton(const Singleton&) = delete;
	Singleton& operator=(const Singleton&) = delete;

};
void worker(){
	Singleton::getInstance().showMessage();
}

//int main() {
//	std::vector<std::thread> threads;
//	std::cout << "Creating threads..." << std::endl;
//	for (int i= 0; i < 5; i++) {
//		threads.emplace_back(worker); //会走thread的构造函数,构造出thread对象,
//		                              //然后传worker给该对象
//	}
//	//主线程join等待
//	for (auto& t : threads) {
//		t.join();
//	}
//	
//	std::cout << "All threads finished." << std::endl;
//	return 0;
//}


//工厂模式：
#include <string>
#include <memory>
class Resource { 
public:     
	//静态工厂方法
	static std::unique_ptr<Resource> create(const std::string& type)
	{
		if (type == "TypeA")
		{
			return std::unique_ptr<Resource>(new Resource("Created TypeA"));
		}
		else if (type == "TypeB")
		{
			return std::unique_ptr<Resource>(new Resource("Created TypeB"));
		}
		return nullptr;
	}
	void use() {}
    const std::string& getInfo() const { return info_; }
private:
   // 私有构造函数，强制通过工厂方法创建Resource对象
   Resource(std::string info):info_(std::move(info)){}
   std::string info_;
   // 禁止拷贝和赋值   
   Resource(const Resource&) = delete;
    Resource& operator=(const Resource&) = delete;
};

int main() {
	auto resA = Resource::create("TypeA");
	// 使用静态工厂方法创建对象   
	if (resA) {
		std::cout << "Resource A info: " << resA->getInfo() << std::endl;
		resA->use();
	}
	auto resB = Resource::create("TypeB");
	if (resB) {
		std::cout << "Resource B info: " << resB->getInfo() << std::endl;
	}
	return 0;
}
